﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Windows.Phone.Speech.Recognition;
using Windows.Networking.Sockets;
using Windows.Networking;
using Windows.Storage.Streams;
using Windows.Networking.Connectivity;
using System.Diagnostics;
using System.Text;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Windows.Phone.Speech.VoiceCommands;
using System.Text.RegularExpressions;
using Microsoft.Phone.Net.NetworkInformation;
using Windows.Phone.Speech.Synthesis;
using System.IO;
using System.ComponentModel;
using System.Collections.ObjectModel;
using Microsoft.Phone.Tasks;

namespace VoiceControl
{
    public partial class MainPage : PhoneApplicationPage
    {
        SpeechRecognizerUI reco_Online;
        SpeechSynthesizer synth;
        // 构造函数
        public MainPage()
        {
            InitializeComponent();

            synth = new SpeechSynthesizer();

            reco_Online = new SpeechRecognizerUI();

            reco_Online.Settings.ListenText = "请说出您需要的操作";
            reco_Online.Settings.ExampleText = "例如：打开Word";

            if (DeviceNetworkInformation.IsNetworkAvailable)
            {
                reco_Online.Recognizer.Grammars.AddGrammarFromPredefinedType("all", SpeechPredefinedGrammar.WebSearch);
            }

            FileList.ItemsSource = App.FileData;
            this.Loaded += MainPage_Loaded;
        }

        async void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            connect();
            await synth.SpeakTextAsync("请按屏幕下方的话筒按钮，并说出 要执行的操作");
        }

        async void DoVoice()
        {
            SpeechRecognitionUIResult recoResult = null;
            if (DeviceNetworkInformation.IsNetworkAvailable)
                recoResult = await reco_Online.RecognizeWithUIAsync();
            else
                new App.ToastTips("网络不可用");
            if (recoResult == null)
            {
                connect();
                return;
            }
            if (recoResult.ResultStatus == SpeechRecognitionUIStatus.Succeeded)
                if (recoResult.ResultStatus == SpeechRecognitionUIStatus.Succeeded)
                {
                    string Result = recoResult.RecognitionResult.Text.ToUpper();
                    if (App.Web.ContainsKey(Result))
                    {
                        Send(App.Web[Result]);
                    }
                    else if (App.WinCommand.ContainsKey(Result))
                    {
                        Send(App.WinCommand[Result]);
                    }
                    else if (App.Office.ContainsKey(Result))
                    {
                        Send(App.Office[Result]);
                    }
                    else
                    {
                        try
                        {
                            string[] SearchInfo = Regex.Split(Result, "搜索");
                            if (SearchInfo.Length >= 2)
                            {
                                SearchInfo[0] = SearchInfo[0].Replace("用", "");
                                if (App.Search.ContainsKey(SearchInfo[0]))
                                {
                                    if (!string.IsNullOrWhiteSpace(SearchInfo[1]))
                                    {
                                        Send("DOSEARCH_" + App.Search[SearchInfo[0]] + "_" + SearchInfo[1]);
                                    }
                                }
                                else if(string.IsNullOrWhiteSpace(SearchInfo[0]))
                                {
                                    Send("DOSEARCH_baidu_" + SearchInfo[1]);
                                }
                            }
                            else if(SearchInfo.Length==1)
                            {
                                reco_Online.Settings.ShowConfirmation = false;
                                await synth.SpeakTextAsync("找不到指令，将用百度搜索");
                                Send("DOSEARCH_baidu_" + SearchInfo[0]);
                            }
                        }
                        catch
                        {
                            MessageBox.Show("您的命令无法处理！");
                        }
                    }
                }
                else
                {
                    await synth.SpeakTextAsync("您的命令无法处理");
                }
        }

        StreamSocket clientSocket = new StreamSocket();
        async void connect()
        {
            try
            {
                HostName serverHost = new HostName(App.Setting.ServerIP);
                await clientSocket.ConnectAsync(serverHost, App.Setting.Port);
                try
                {
                    string JsonData = JsonConvert.SerializeObject(new UserInfo
                    {
                        name = "yy_phone",
                        password = "123456"
                    });
                    DataWriter writer = new DataWriter(clientSocket.OutputStream);
                    string content = "Login#" + JsonData;

                    byte[] data = Encoding.UTF8.GetBytes(content);
                    writer.WriteBytes(data);

                    await writer.StoreAsync();
                    writer.DetachStream();
                    writer.Dispose();
                    DataReader reader = new DataReader(clientSocket.InputStream);
                    reader.InputStreamOptions = InputStreamOptions.Partial;
                    await reader.LoadAsync(1024);
                    string response = reader.ReadString(reader.UnconsumedBufferLength);
                    Debug.WriteLine(response);
                    Dispatcher.BeginInvoke(() =>
                    {
                        new App.ToastTips("连接已建立");
                    });
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e);
                    clientSocket.Dispose();
                    clientSocket = null;
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
                clientSocket.Dispose();
                clientSocket = null;
            }
        }

        DataWriter writer = null;
        async void Send(string Command)
        {
            try
            {
                string JsonData = JsonConvert.SerializeObject(new MsgInfo
                {
                    name = "yy_phone",
                    msg = Command,
                    destname = "yy_computer"
                });

                writer = new DataWriter(clientSocket.OutputStream);
                string content = "Info#" + JsonData;

                byte[] data = Encoding.UTF8.GetBytes(content);
                writer.WriteString(content);
                await writer.StoreAsync();
                await writer.FlushAsync();
                writer.DetachStream();
                writer.Dispose();
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
                clientSocket.Dispose();
                clientSocket = null;
            }
        }

        private void BB_Click(object sender, EventArgs e)
        {
            switch (Index.SelectedIndex)
            {
                case 0:
                    DoVoice();
                    break;
                case 1:
                    DoFileVoice();
                    break;
            }
        }

        SpeechRecognizerUI FileVoice;
        async void DoFileVoice()
        {
            if (App.FileData.Count == 0)
                return;
            FileVoice = new SpeechRecognizerUI();
            FileVoice.Recognizer.Grammars.AddGrammarFromList("filename", App.FileNames);
            FileVoice.Recognizer.Grammars.AddGrammarFromList("email", App.EmailFile);
            FileVoice.Settings.ListenText = "请说出需要获取的文件名";
            FileVoice.Settings.ExampleText = "例如：" + App.FileNames[0];
            var Result = await FileVoice.RecognizeWithUIAsync();
            if (Result.ResultStatus == SpeechRecognitionUIStatus.Succeeded)
            {
                string resultStr = Result.RecognitionResult.Text;
                if(resultStr.Contains("给") && resultStr.Contains("发送"))
                {
                    //try
                    //{
                    //    string[] FileSendInfo = Regex.Split(resultStr, "发送");
                    //    FileSendInfo[0] = FileSendInfo[0].Replace("给", "");
                    //}
                    new App.ToastTips("发送成功");

                    return;
                }
                int arrayIndex = App.FileNames.IndexOf(Result.RecognitionResult.Text);
                WebBrowserTask task = new WebBrowserTask();
                task.URL=App.FileData[arrayIndex].Url;
                task.Show();
            }
        }
        private void BB_Connect_Click(object sender, EventArgs e)
        {
            switch (Index.SelectedIndex)
            {
                case 0:
                    if (clientSocket == null)
                        connect();
                    break;
                case 1:
                    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://222.24.63.111:88/JspUpDownTest/servlet/JsonFile?" + DateTime.Now.Millisecond);
                    request.BeginGetResponse(new AsyncCallback(getResponse), request);
                    break;
            }
        }

        void getResponse(IAsyncResult result)
        {
            HttpWebRequest req = (HttpWebRequest)result.AsyncState;
            HttpWebResponse response = (HttpWebResponse)req.EndGetResponse(result);
            Stream stream = response.GetResponseStream();
            using (StreamReader reader = new StreamReader(stream))
            {
                string str = reader.ReadToEnd();
                Dispatcher.BeginInvoke(() =>
                    {
                        try
                        {
                            JArray array = JArray.Parse(str);
                            if (App.FileData.Count != 0)
                            {
                                App.FileData.Clear();
                                App.FileNames.Clear();
                            }
                            foreach (var item in array)
                            {
                                App.FileData.Add(new FileInfo
                                {
                                    Name = (string)item["fileName"],
                                    Size = (string)item["fileSize"]
                                });
                                string tmp = ((string)item["fileName"]).Substring(0, ((string)item["fileName"]).IndexOf("."));
                                App.FileNames.Add(tmp);
                                App.EmailFile.Add("给金航发送" + tmp);
                            }
                        }
                        catch
                        {
                            new App.ToastTips("文件列表获取失败");
                        }
                    });
            }
        }

    }

    #region //信息类
    class UserInfo
    {
        public string name { set; get; }
        public string password { set; get; }
    }

    class MsgInfo
    {
        public string name { set; get; }
        public string msg { set; get; }
        public string destname { set; get; }
    }

    
#endregion
}

public class FileInfo : INotifyPropertyChanged
{
    private string _Name;
    public string Name
    {
        set
        {
            if (value != _Name)
            {
                _Name = value;
                NotifyPropertyChanged("Name");
            }
        }
        get
        {
            return _Name;
        }
    }

    public string _Size;
    public string Size
    {
        set
        {
            if (value != _Size)
            {
                _Size = value;
                NotifyPropertyChanged("Size");
            }
        }
        get
        {
            return _Size;
        }
    }
    public string Url
    {
        get
        {
            return "http://222.24.63.111:88/JspUpDownTest/servlet/DowFileByName?filename=" + Name;
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged(String propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (null != handler)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}